<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="login-title">系统登录</div>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="login-btn" @click="handleLogin" :loading="loginLoading">
            {{ loginLoading ? '登录中' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useGlobalStore } from '@/store/modules/global'
import { ElMessage } from 'element-plus'
import { loginReq } from '@/api/common/index'
import { initDynamicRouter } from '@/router'

const router = useRouter()
const globalStore = useGlobalStore()
const loginFormRef = ref()

const loginForm = reactive({
  username: 'admin',
  password: '123456'
})

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

// 登录按钮
const loginLoading = ref(false)
const handleLogin = async () => {
  try {
    loginLoading.value = true
    await loginFormRef.value.validate()
    const res = await loginReq({
      password: '123456',
      username: 'admin'
    })

    // 存入 token 和用户信息到 pinia 中
    if (res.code === 1) {
      globalStore.setToken(res.data.token)
      globalStore.setUserInfo({
        id: res.data.id,
        userName: res.data.userName,
        name: res.data.name
      })

      // 动态路由初始化
      await initDynamicRouter()

      ElMessage.success('登陆成功')

      // 获取跳转路径
      const redirect = (router.currentRoute.value.query.redirect as string) || '/layout'
      router.push(redirect)
    }
  } catch (error) {
    console.error('登录失败', error)
  } finally {
    loginLoading.value = false
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.login-card {
  width: 400px;
  padding: 20px;
}

.login-title {
  text-align: center;
  font-size: 20px;
  margin-bottom: 20px;
  color: #333;
}

.login-btn {
  width: 100%;
}
</style>
